package com.qk.management.web.interceptor;

import cn.hutool.http.HttpStatus;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;

/**
 * @文件名: LoginCheckInterceptor
 * @作者: DX
 * @创建日期: 2025/10/11
 * @描述:
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    private static final String TOKEN_HEADER = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

        Optional<String> token = Optional.ofNullable(request.getHeader(TOKEN_HEADER));
        if (token.isEmpty()) {
            log.error("请求token为空");
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }

        try {
            Claims claims = JwtUtils.parseToken(token.get());
            Integer id = claims.get("id", Integer.class);
            log.info("id: {}", id);
            CurrentUserContextHolders.set(id);
            String username = claims.get("username", String.class);
            log.info("username: {}", username);
            return true;
        } catch (Exception e) {
            log.error("token解析失败", e);
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUserContextHolders.remove();
    }
}